package com.ruoyi.cms.folder.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cms.folder.domain.CmsFolder;
import com.ruoyi.cms.folder.service.ICmsFolderService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 文件夹Controller
 * 
 * @author ning
 * @date 2023-06-25
 */
@RestController
@RequestMapping("/cms/folder")
public class CmsFolderController extends BaseController
{
    @Autowired
    private ICmsFolderService cmsFolderService;

    /**
     * 查询文件夹列表
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:list')")
    @GetMapping("/list")
    public AjaxResult list(CmsFolder cmsFolder)
    {
        List<CmsFolder> list = cmsFolderService.selectCmsFolderList(cmsFolder);
        return success(list);
    }

    /**
     * 查询文件夹列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:list')")
    @GetMapping("/list/exclude/{folderId}")
    public AjaxResult excludeChild(@PathVariable(value = "folderId", required = false) Long folderId)
    {
        List<CmsFolder> folderIds = cmsFolderService.selectCmsFolderList(new CmsFolder());
        folderIds.removeIf(d -> d.getFolderId().intValue() == folderId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), folderId + ""));
        return success(folderIds);
    }

    /**
     * 导出文件夹列表
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:export')")
    @Log(title = "文件夹", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmsFolder cmsFolder)
    {
        List<CmsFolder> list = cmsFolderService.selectCmsFolderList(cmsFolder);
        ExcelUtil<CmsFolder> util = new ExcelUtil<CmsFolder>(CmsFolder.class);
        util.exportExcel(response, list, "文件夹数据");
    }

    /**
     * 获取文件夹详细信息
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:query')")
    @GetMapping(value = "/{folderId}")
    public AjaxResult getInfo(@PathVariable("folderId") Long folderId)
    {
        cmsFolderService.checkCmsFolderDataScope(folderId);
        return success(cmsFolderService.selectCmsFolderByFolderId(folderId));
    }

    /**
     * 新增文件夹
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:add')")
    @Log(title = "文件夹", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmsFolder cmsFolder)
    {
        if (!cmsFolderService.checkCmsFolderNameUnique(cmsFolder))
        {
            return error("新增文件夹'" + cmsFolder.getFolderName() + "'失败，文件夹名称已存在");
        }
        cmsFolder.setCreateBy(getUsername());
        return toAjax(cmsFolderService.insertCmsFolder(cmsFolder));
    }

    /**
     * 修改文件夹
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:edit')")
    @Log(title = "文件夹", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmsFolder cmsFolder)
    {
        Long folderId = cmsFolder.getFolderId();
        cmsFolderService.checkCmsFolderDataScope(folderId);
        if (!cmsFolderService.checkCmsFolderNameUnique(cmsFolder))
        {
            return error("修改文件夹'" + cmsFolder.getFolderName() + "'失败，文件夹名称已存在");
        }
        else if (cmsFolder.getParentId().equals(folderId))
        {
            return error("修改文件夹'" + cmsFolder.getFolderName() + "'失败，上级文件夹不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, cmsFolder.getStatus()) && cmsFolderService.selectNormalChildrenFolderById(folderId) > 0)
        {
            return error("该文件夹包含未停用的子文件夹！");
        }
        else if (cmsFolder.getParentId()!=0)
        {
            CmsFolder parentFolder = cmsFolderService.selectCmsFolderByFolderId(cmsFolder.getParentId());
            if (parentFolder.getAncestors().contains(String.valueOf(cmsFolder.getFolderId())))
            {
                return error("修改文件夹'" + cmsFolder.getFolderName() + "'失败，上级文件夹不能是自己的子文件夹");
            }
        }
        cmsFolder.setUpdateBy(getUsername());
        return toAjax(cmsFolderService.updateCmsFolder(cmsFolder));
    }

    /**
     * 删除文件夹
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:remove')")
    @Log(title = "文件夹", businessType = BusinessType.DELETE)
	@DeleteMapping("/{folderIds}")
    public AjaxResult remove(@PathVariable Long[] folderIds)
    {
        for (Long folderId : folderIds) {
            if (cmsFolderService.hasChildByFolderId(folderId))
            {
                return warn("存在下级文件夹,不允许删除");
            }
            if (cmsFolderService.checkFolderExistDocs(folderId))
            {
                return warn("文件夹存在文件,不允许删除");
            }
            cmsFolderService.checkCmsFolderDataScope(folderId);
        }
        return toAjax(cmsFolderService.deleteCmsFolderByFolderIds(folderIds));
    }

    /**
     * 获取文件夹树列表
     */
    @PreAuthorize("@ss.hasPermi('cms:folder:list')")
    @RequestMapping("/folderTreeList")
    public AjaxResult folderTreeList(CmsFolder cmsFolder)
    {
        return success(cmsFolderService.selectFolderTreeList(cmsFolder));
    }
}
